{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 单量子比特门\n",
    "\n",
    "*版权所有 (c) 2021 百度量子计算研究所，保留所有权利。*"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 内容概要\n",
    "本教程介绍如何产生高保真度的单量子比特门的脉冲。本教程的大纲如下：\n",
    "- 背景介绍\n",
    "- 准备工作\n",
    "- 构造哈密顿量\n",
    "- 生成 Hadamard 门的优化脉冲\n",
    "- 生成 X 门的优化脉冲\n",
    "- 生成 Z 门的优化脉冲\n",
    "- 生成任意单量子比特门的优化脉冲\n",
    "- 总结"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 背景介绍\n",
    "我们将对量子比特的操作称为**量子门**，而在超导量子比特中，量子门操作往往通过在量子比特上施加外部微波脉冲驱动和用于调控量子比特的磁通，从而实现量子态的演化。单量子比特门可以表示为酉算符 $U$，数学上可以用一个 $2\\times2$ 的酉矩阵来表示。单量子比特门操作也可以用布洛赫球 (Bloch Sphere) 上态矢量 $|\\psi\\rangle$ 的演化来表示，其中 $|\\psi\\rangle=\\cos(\\theta/2)|0\\rangle+e^{i\\phi}\\sin(\\theta/2)|1\\rangle$ 表示两个量子态 $|0\\rangle$ 和 $|1\\rangle$ 的叠加态。通过进行单量子比特门操作，我们可以实现不同量子态在布洛赫球面上的转化 \\[1\\]。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![bloch sphere](figures/sphere.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们总结了一些典型的单量子比特门及其算符和矩阵形式，如下表所示："
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "| 量子门   |      布洛赫球上的操作      |  算符 | 矩阵形式 | \n",
    "|----------|:-------------:|:-:|:-:|\n",
    "| $X$ |  绕 $x$ 轴旋转 $\\pi$ 的角度 | $\\hat{\\sigma}_x$ | $\\left(\\begin{array}{cc} 0 & 1\\\\1 & 0\\end{array}\\right)$ |\n",
    "| $Y$ |  绕 $y$ 轴旋转 $\\pi$ 的角度 | $\\hat{\\sigma}_y$ |$\\left(\\begin{array}{cc} 0 & -i\\\\i & 0\\end{array}\\right)$ |\n",
    "| $Z$ |  绕 $z$ 轴旋转 $\\pi$ 的角度 | $\\hat{\\sigma}_z$ |$\\left(\\begin{array}{cc} 1 & 0\\\\0 & -1\\end{array}\\right)$ |\n",
    "| $S$ |  绕 $z$ 轴旋转 $\\pi \\over 2$ 的角度 |  |$\\left(\\begin{array}{cc} 1 & 0\\\\0 & e^{i\\frac{\\pi}{2}}\\end{array}\\right)$ |\n",
    "| $T$ |  绕 $z$ 轴旋转 $\\pi \\over 4$ 的角度 |  |$\\left(\\begin{array}{cc} 1 & 0\\\\0 & e^{i\\frac{\\pi}{4}}\\end{array}\\right)$ |\n",
    "| $H$ | 先绕 $x$ 轴旋转 $\\pi$ 的角度，再绕 $z$ 轴旋转 $\\pi \\over 2$ 的角度 |  |$\\frac{1}{\\sqrt{2}}\\left(\\begin{array}{cc} 1 & 1\\\\1 & -1\\end{array}\\right)$ |"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**量脉中的单量子门**\n",
    "\n",
    "\n",
    "在量脉中，对单个量子比特的任意操作都是通过以下等式实现的（包含了一个全局相位项，这里没有 $R_x$ 分量）：\n",
    "$$\n",
    "U(\\theta, \\phi, \\lambda) = e^{i(\\phi/2+\\lambda/2)} R_z(\\phi) R_y(\\theta) R_z(\\lambda) =\n",
    "\\begin{bmatrix} \n",
    "    \\cos(\\theta/2) & - e^{i\\lambda} \\sin(\\theta/2) \\\\\n",
    "    e^{i\\phi} \\sin(\\theta/2) & e^{i(\\phi + \\lambda)} \\cos(\\theta/2)\n",
    "\\end{bmatrix} ,\n",
    "$$\n",
    "\n",
    "其中， $e^{i(\\phi/2+\\lambda/2)}$ 是全局相位。\n",
    "\n",
    "\n",
    "有关其他门的更多信息，请参阅我们的[API文档](https://quanlse.baidu.com/api/)。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在我们简单介绍一下单量子比特门物理实现的原理。在超导量子比特上，有两种实现单量子比特门的方法：\n",
    "\n",
    "- **微波控制**通过向超导量子比特施加微波脉冲信号进行调控（X，Y 通道控制）。\n",
    "\n",
    "- **磁通调控**通过施加局部磁场改变量子比特的共振频率（Z 通道控制）。\n",
    "\n",
    "下图描绘了超导量子比特的 X/Y/Z 通道：\n",
    "\n",
    "![X/Y/Z controls for single superconducting qubit](figures/hardware_qubit_control.png)\n",
    "\n",
    "**微波脉冲的实现**\n",
    "\n",
    "实验上，为了实现对超导量子比特的微波调控（X，Y 通道调控），需要先由本机振荡器（Local Oscillator）产⽣一个高频的微波信号，频率记为 $\\omega_{\\rm LO}$，然后再⽤低频的信号进行调制。通常，低频信号由任意波发生器（Arbitrary Wave Generator）产生，频率记为 $\\omega_{\\rm AWG}$。最后我们可以得到频率 $\\omega_{d}=\\omega_{\\rm LO}\\pm\\omega_{\\rm AWG}$ 的高斯型或正切等函数型包络的脉冲。需要指出的是，此处以及后面提及的频率均指的是角频率。\n",
    "\n",
    "**磁通脉冲的实现**\n",
    "\n",
    "实现磁通调控（Z 通道调控），常见的做法是将单个约瑟夫森结替换为超导量子干涉仪 (Superconducting Quantum Interference Device)，即一个由两个约瑟夫森结构成的闭环。通过向垂直于闭环的方向施加外部磁场，可以实现对量子比特频率的调控。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 准备工作\n",
    "\n",
    "成功安装量脉后，您可以按照本教程运行下面的量脉程序。在运行此教程前，您需要从量脉（Quanlse）和其它常用的 Python 库导入以下包："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Import numpy and math\n",
    "from numpy import round\n",
    "from math import pi\n",
    "\n",
    "# Import the Hamiltonian module\n",
    "from Quanlse.QHamiltonian import QHamiltonian as QHam\n",
    "\n",
    "# Import simulator interface on Quanlse Cloud Service\n",
    "from Quanlse.remoteOptimizer import remoteOptimize1Qubit\n",
    "\n",
    "# Import related packages\n",
    "from Quanlse.Utils.Functions import project\n",
    "from Quanlse.QOperator import duff\n",
    "from Quanlse.QOperation import FixedGate"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 构造哈密顿量\n",
    "\n",
    "现在，我们将展示如何使用量脉实现单量子比特门。在这个教程中，我们将模拟一个由一个三能级 transmon 组成的系统。在理想情况下，超导量子比特中失谐性带来的能级差允许调整驱动频率对能级跃迁进行选择性驱动。然而，由于 transmon 量子比特的失谐性较弱，再加上驱动场的频率带宽有限，从而计算空间中的量子态可能会被激发至更高的能级，从而产生能级泄露。在我们的模型中，我们将超导量子比特视为一个简化的三能级系统，从而考虑了泄露到 $| 2\\rangle$ 能级的情况。在旋转坐标系（Rotating Frame）中，描述该三能级量子系统的哈密顿量可以写为 \\[2\\]：\n",
    "\n",
    " $$\n",
    " \\hat{H}=\\alpha_q\\lvert2\\rangle\\langle 2\\lvert+\\frac{\\Omega^x(t)}{2}\\left[ \\hat{a}^\\dagger + \\hat{a} \\right] + \\frac{\\Omega^y(t)}{2} i \\left[\\hat{a}^\\dagger - \\hat{a}\\right]+\\Omega^z(t)\\hat{a}^{\\dagger}\\hat{a},\n",
    " $$\n",
    "\n",
    "其中 $\\alpha_q$ 是失谐频率; $\\Omega^x(t)$ 是 X 通道的驱动脉冲的强度；$\\Omega^y(t)$ 是 Y 通道的驱动脉冲强度；$\\Omega^z(t)$ 是 Z 通道的磁通脉冲强度。这里，$\\hat{a}^\\dagger = |1\\rangle\\langle 0| + \\sqrt{2}|2\\rangle\\langle 1|$ 和 $\\hat{a} = |0\\rangle\\langle 1| + \\sqrt{2}|1\\rangle\\langle 2|$ 分别是产生和湮灭算符。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "量脉可以用来于实现任意的单量子比特门。量脉支持各种波形的定义，这里我们以高斯脉冲为例。高斯脉冲函数的形式如下：\n",
    "$$\n",
    "A^{x}(t)=A^{x} e^{-((t-\\tau^{x})/2\\sigma^{x})^2}, \n",
    "$$\n",
    "\n",
    "$$\n",
    "A^{y}(t)=A^{y} e^{-((t-\\tau^{y})/2\\sigma^{y})^2} .\n",
    "$$\n",
    "上面的等式中， $A^{x}, A^{y}, \\tau^{x}, \\tau^{y}, \\sigma^{x}, \\sigma^{y}$ 是待优化的参数。与微波控制不同，磁通量的输入采用方波的形式，$A^{z}(t) = A^{z}$ ，其中 $A^{z}$ 是待优化的参数。\n",
    "\n",
    "现在，我们需要用量脉来构造上面的哈密顿量。在量脉中，所有关于哈密顿量的信息都存储在一个哈密顿量对象中。首先，我们定义构建哈密顿量所需的一些基本参数：采样周期、系统中的量子比特数、以及要考虑的系统能级："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Sampling period\n",
    "dt = 0.2\n",
    "\n",
    "# Number of qubits\n",
    "qubits = 1\n",
    "\n",
    "# System energy level\n",
    "level = 3"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "然后，我们定义量子比特的失谐频率："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define anharmonicity\n",
    "qubitArgs = {\n",
    "    \"qubit_anharm\": - 0.33 * (2 * pi),  # Anharmonicity of the qubit\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "最后，我们使用 `QHam()` 实例化一个哈密顿量对象，并同时传入我们上面定义的参数。然后我们通过 `addDrift()` 方法加入比特的失谐项。该方法参数包括失谐项算符，量子比特索引编号和失谐项的强度。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create the Hamiltonian.\n",
    "ham = QHam(qubits, level, dt)\n",
    "\n",
    "# Add the drift term(s).\n",
    "ham.addDrift(duff, 0, coef=qubitArgs[\"qubit_anharm\"] / 2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 生成 Hadamard 门的优化脉冲\n",
    "\n",
    "创建了系统哈密顿量之后，我们可以使用 `remoteOptimize1Qubit()` 方法生成并优化脉冲（这里我们先以 Hadamard 门为例）。该方法参数包括一个哈密顿量对象，目标比特门，最大脉冲数量，以及目标保真度。在本地设备上进行优化通常需要很长时间，但是，我们提供的云服务可以显著加快这一过程。在使用量脉云服务之前，用户需要从 http://quantum-hub.baidu.com 获取一个 token，并使用以下命令将任务提交到量脉的服务器上。对于这个例子，我们可以通过以下代码实现："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Import Define class and set the token\n",
    "# Please visit http://quantum-hub.baidu.com\n",
    "from Quanlse import Define\n",
    "Define.hubToken = ''\n",
    "\n",
    "# Run the optimization\n",
    "gateJob, infidelity = remoteOptimize1Qubit(ham, FixedGate.H.getMatrix(), depth=4, targetInfid=0.0001)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在本教程中，我们用这个公式来定义量子门的失真度： ${\\rm infid} = 1 - \\frac{1}{d}\\left|{\\rm Tr}[U^\\dagger_{\\rm goal}P(U)]\\right|$，其中 $U{\\rm goal}$ 是单量子比特门的目标演化的酉矩阵； $d$ 是 $U{\\rm goal}$ 的维度；$U$ 是实际演化的酉矩阵。这里，$P(U)$ 是投影到计算空间的演化算符。\n",
    "\n",
    "在这个例子中，我们选择只在 X 和 Y 通道上产生脉冲。我们可以看到，我们生成了保真度较高的脉冲，我们鼓励用户尝试改变这些参数以获得最佳结果。\n",
    "\n",
    "`plot()` 方法允许我们将生成的脉冲可视化。我们还可以通过 `simulate()`和 `project()` 方法得到表示系统演化的矩阵："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Print infidelity and the waveforms\n",
    "print(f\"minimum infidelity: {infidelity}\")\n",
    "gateJob.plot(dark='True')\n",
    "\n",
    "# Print the evolution process.\n",
    "result = ham.simulate(job=gateJob)\n",
    "projectedEvolution = project(result.result[0][\"unitary\"], qubits, level, 2)\n",
    "print(\"Projected evolution:\\n\", round(projectedEvolution, 2))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`plot()` 的方法参数包括一个可选的 bool 参数 `dark`（该参数为 `True` 时启用暗色模式）。此外，用户可以使用 `color` 参数为脉冲指定颜色（如果脉冲数多于颜色数，颜色将重复）。（其它参数请参见 API ）\n",
    "\n",
    "下面是优化 X 门、Z 门和任意单量子门脉冲的演示，使用的是我们在上文中已经定义的系统哈密顿量。\n",
    "\n",
    "## 生成 X 门的优化脉冲\n",
    "\n",
    "以下代码演示如何生成并优化一个 X 门的脉冲，该过程类似上述对 Hadamard 门的优化过程。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Run the optimization\n",
    "gateJob, infidelity = remoteOptimize1Qubit(ham, FixedGate.Z.getMatrix(), depth=4, targetInfid=0.0001)\n",
    "\n",
    "# Print infidelity and the waveforms\n",
    "print(f\"minimum infidelity: {infidelity}\")\n",
    "gateJob.plot(dark='True')\n",
    "\n",
    "# Print the evolution process.\n",
    "result = ham.simulate(job=gateJob)\n",
    "projectedEvolution = project(result.result[0][\"unitary\"], qubits, level, 2)\n",
    "print(\"Projected evolution:\\n\", round(projectedEvolution, 2))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 生成 Z 门的优化脉冲\n",
    "\n",
    "下面的代码生成并优化一个 Z 门的脉冲，同样地，该过程与上文所介绍的优化过程相似。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Run the optimization\n",
    "gateJob, infidelity = remoteOptimize1Qubit(ham, FixedGate.Z.getMatrix(), depth=4, targetInfid=0.0001)\n",
    "\n",
    "# Print infidelity and the waveforms\n",
    "print(f\"minimum infidelity: {infidelity}\")\n",
    "gateJob.plot(dark='True')\n",
    "\n",
    "# Print the evolution process.\n",
    "result = ham.simulate(job=gateJob)\n",
    "projectedEvolution = project(result.result[0][\"unitary\"], qubits, level, 2)\n",
    "print(\"Projected evolution:\\n\", round(projectedEvolution, 2))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 生成任意单量子比特门的优化脉冲\n",
    "\n",
    "以下代码生成并优化任意单量子门 `U（θ=-1.231，φ=1.231，lamda=-1.231）`的脉冲。这里，用户需要从 `RotationGate` 导入 `U`。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from Quanlse.QOperation.RotationGate import U\n",
    "\n",
    "# Define a U3 gate\n",
    "aGate = U(theta=-1.231, phi=1.231, lamda=-1.231)\n",
    "\n",
    "# Run the optimization\n",
    "gateJob, infidelity = remoteOptimize1Qubit(ham, aGate.getMatrix(), depth=4, targetInfid=0.0001)\n",
    "\n",
    "# Print infidelity and the waveforms\n",
    "print(f\"minimum infidelity: {infidelity}\")\n",
    "gateJob.plot(dark='True')\n",
    "\n",
    "# Print the evolution process.\n",
    "result = ham.simulate(job=gateJob)\n",
    "projectedEvolution = project(result.result[0][\"unitary\"], qubits, level, 2)\n",
    "print(\"Projected evolution:\\n\", round(projectedEvolution, 2))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "## 总结\n",
    "\n",
    "\n",
    "本教程介绍了使用量脉为任何单量子比特门生成和优化脉冲的完整过程。用户可以点击这个链接 [tutorial-single-qubit-gate.ipynb](https://github.com/baidu/Quanlse/blob/main/Tutorial/CN/tutorial-single-qubit-cn.ipynb) 跳转到此 Jupyter Notebook 文档相应的 GitHub 页面来获得相关代码以运行程序。我们鼓励用户尝试不同于本教程的参数值以获得最佳结果。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 参考文献\n",
    "\n",
    "\\[1\\] [Nielsen, Michael A., and Isaac L. Chuang. Quantum Computation and Quantum Information: 10th Anniversary Edition. Cambridge University Press, 2010.](https://doi.org/10.1017/CBO9780511976667)\n",
    "\n",
    "\\[2\\] [Wilhelm, Frank K., et al. \"An introduction into optimal control for quantum technologies.\" *arXiv preprint arXiv:2003.10132* (2020).](https://arxiv.org/abs/2003.10132)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
